package cn.itcast.travel.web.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成方法分发
        //1.获取请求路径
        String url = req.getRequestURI();
        System.out.println(url);
        //2.获取方法名称
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        System.out.println(methodName);
        //3.获取方法名对象Method
        //谁调用我,我代表谁
        System.out.println(this);//this UserServlet对象
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);/*这两个方法不能写反,写反了不能运行*/
            //暴力反射
            method.setAccessible(true);
            System.out.println(method);
            //4.执行方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 直接将传入的对象序列化为json,并写回客户端
     *
     * @param obj
     * @param response
     * @throws Exception
     */
    public void writeValue(Object obj, HttpServletResponse response) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(), obj);
    }

    /**
     * 将传入的对象序列化为json，返回
     *
     * @param obj
     * @return
     */
    public String writeValueAsString(Object obj) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(obj);
    }
}
